//
//  VideoListController.m
//  cooba-iOS
//
//  Created by 郭四虎 on 16/5/10.
//  Copyright © 2016年 YouKu. All rights reserved.
//

#import "VideoListController.h"
#import "VideoListModel.h"
#import "VideoListCell.h"


@interface VideoListController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger next_key;
    UILabel *_msgLb;
}



@end
@implementation VideoListController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTable) name:@"FailToReceive" object:nil];
    
    self.dataArr = [NSMutableArray array];
    next_key = 0;
    
    CGRect rect = self.view.bounds;
    rect.size.height -= 60;
    
    self.view.frame = rect;
    [self initUI];
}
- (void)refreshTable
{
    [self.table reloadData];
}
- (void)initUI
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64- 48)];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.table];
    self.table.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.table.layer.borderWidth = 1;
    
    [_table registerNib:[UINib nibWithNibName:@"VideoListCell" bundle:nil] forCellReuseIdentifier:@"VideoListCell"];
    
    self.table.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(createContentData)];
    self.table.header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
}
- (void)refresh
{
    next_key = 0;
    [self.dataArr removeAllObjects];
    [self.table reloadData];
    [self createContentData];
}

- (void)createData
{
    [self createContentData];
    [self creatHeader];
}
-(void)creatHeader
{
    [[MyAd sharedMyad]headerViewwithTag:self.adkey target:self back:^(UIView *headView,NSArray *dataArr,bool iserror) {
        
        self.table.tableHeaderView = headView;
        [self.table reloadData];
        _msgLb.frame = CGRectMake(20, SCALEY*(179)+90+20, WIDTH - 40, 50);
        
        self.scrollView = (SDCycleScrollView *)headView;
        self.adArr = dataArr;
        self.collectAd(self.scrollView,self.adArr,iserror);
        self.scrollView.shouldGetoffset = YES;
    }];
}
- (void)createContentData
{
    if (next_key == 1000) {
        [self.view Message:@"亲,已经到底了" HiddenAfterDelay:1];
        [self.table.footer endRefreshing];
        return;
    }
    
    NSDictionary *dic = @{@"next_key":@(next_key),@"dir_name":_model.sortid,@"page_size":@(10)};
    //@"http://test4.cooba.cc/index.php/Port/videoPortInfo"
    
    NSString *url;
    if([ISBUS boolValue]){
        url = [NSString stringWithFormat:@"%@/Port/videoPortInfo",CAR_URL];
    }else{
        url = VIDEOLIST;
    }
    [MyAFN POST:url  parameters:dic block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        
        if ([[response objectForKey:@"status"]integerValue]) {
            
            
            if ([[response objectForKey:@"next_key"]integerValue]) {
                next_key = [[response objectForKey:@"next_key"] integerValue];
            }else{
                next_key = 1000;
            }
            [[EGOCache globalCache]setObject:response forKey:[NSString stringWithFormat:@"%@videolist",self.title]];
            
        }
        [self getContent:response];
        [_table.header endRefreshing];
        [_table.footer endRefreshing];
        
    }error:^(NSError *error) {
        
        if ([[EGOCache globalCache]objectForKey:[NSString stringWithFormat:@"%@videolist",self.title]]) {
            
            NSDictionary *dic = (NSDictionary *)[[EGOCache globalCache]objectForKey:[NSString stringWithFormat:@"%@videolist",self.title]];
            [self getContent:dic];
            
        }else{
            [self showMessage];
        }
        
        [_table.header endRefreshing];
        [_table.footer endRefreshing];
    } fromController:self];
    
}
-(void)getContent:(NSDictionary *)response
{
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *dic in [response objectForKey:@"videoList"]) {
        
        VideoListModel *model = [[VideoListModel alloc]init];
        [model setValuesForKeysWithDictionary:dic];
        [arr addObject:model];
    }
    
    if (arr.count) {
        
        if (arr.count >=5) {
            [arr insertObject:@"ad" atIndex:5];
            [arr addObject:@"ad"];
        }
        [self.dataArr addObjectsFromArray:arr];
    }
    
    if (self.dataArr.count == 0) {
        [self showMessage];
    }else{
        [self hideMessage];
        [_table reloadData];
    }
}

- (void)showMessage
{
    if (!_msgLb) {
        _msgLb = [[UILabel alloc]init];
    }
    
    if (!self.table.tableHeaderView) {
        _msgLb.frame = CGRectMake(20, 20, WIDTH - 40, 50);
    }else{
        _msgLb.frame = CGRectMake(20, SCALEY*(179)+90+20, WIDTH - 40, 50);
    }
    _msgLb.text = @"暂时没有资源";
    _msgLb.textAlignment = NSTextAlignmentCenter;
    _msgLb.textColor = [UIColor lightGrayColor];
    _msgLb.font = [UIFont systemFontOfSize:18];
    [_table addSubview:_msgLb];
}

- (void)hideMessage
{
    [_msgLb removeFromSuperview];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoListModel *model = [self.dataArr objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[NSString class]]) {
        if (self.isFailReceive) {
            return 0;
        }else{
            return GDTMOB_AD_SUGGEST_SIZE_320x50.height+5;
        }
        
    }else{
        return 220*SCALEY;
    }
    return 220*SCALEY;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    VideoListModel *model = [self.dataArr objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[NSString class]]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aaa"];
        }
        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        if ((indexPath.row+1)%12) {
            [cell.contentView addSubview:self.bannerView2];
        }else{
            [cell.contentView addSubview:self.bannerView];
        }
        
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"VideoListCell" forIndexPath:indexPath];
        VideoListCell *vCell = (VideoListCell *)cell;
        [vCell showModel:model];
    }
    
    return cell;
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    return @"aa";
//}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView.tableHeaderView) {
        return GDTMOB_AD_SUGGEST_SIZE_320x50.height+5;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tableHeaderView) {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, GDTMOB_AD_SUGGEST_SIZE_320x50.height+10)];


        
        [view addSubview:self.bannerView];
        return view;
    }
    return nil;
}
- (void)btnClick
{
    self.otheradclick();
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoListModel *model = [self.dataArr objectAtIndex:indexPath.row];
    if ([model isKindOfClass:[NSString class]]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    self.passModel(model);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"点击%ld",(long)index);
    if (!self.adArr.count) {
        return;
    }
    BannerModel *model = [self.adArr objectAtIndex:index];
    
    self.myad(model);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 190;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


@end
